#coding=utf-8
'''
Created on 2017-08-13

@author: sandy
'''

from threading import Thread
from email.utils import formatdate
import logging
import smtplib
import time
import socket
import string

EMAIL_SUBJECT             = u"GameServer Error"
EMAIL_TO                  = [u'dellzhang@sina.cn']
EMAIL_HOST                = u'smtp.163.com'
EMAIL_PORT                = 465
EMAIL_FROM                = u'zhangyadong.1219@163.com'
EMAIL_USERNAME            = u'zhangyadong.1219@163.com'
EMAIL_PASSWD              = u'zhangyadong1219'
EMAIL_CONCURRENT          = 10
EMAIL_INTERVAL            = 60


class Log2MailCtx():
    
    def __init__(self):
        self.servername = u''
        self.enable = True
        self.concurrent = 0
        self.queuesize = 10
        self.sendtime = []

    def check(self):
        if not self.enable:
            return False
        if self.concurrent > EMAIL_CONCURRENT:
            return False
        if len(self.sendtime) == self.queuesize:
            t = self.sendtime[0]
            if time.time() < t + EMAIL_INTERVAL * (self.queuesize + 1):
                return False
        return True

    def beginSend(self):
        self.concurrent += 1

    def endSend(self):
        self.concurrent -= 1
        if len(self.sendtime) >= self.queuesize:
            self.sendtime.pop(0)
        self.sendtime.append(time.time())

log2mailctx = Log2MailCtx()

def sendMailFunc(mailhost,port,username,passwd,fromaddr,toaddr,msg):
    smtp = smtplib.SMTP_SSL(mailhost,port)
    smtp.login(username,passwd)
    smtp.sendmail(fromaddr,toaddr,msg)
    smtp.quit()

def sendLogMailFunc(mailhost,port,username,passwd,fromaddr,toaddr,msg):
    log2mailctx.beginSend()
    try:
        sendMailFunc(mailhost,port,username,passwd,fromaddr,toaddr,msg)
    finally:
        log2mailctx.endSend()

def sendLogMail(subject,msg):
    msg = "From:%s\r\nTo:%s\r\nSubject:%s\r\nDate:%s\r\n\r\n%s" % (EMAIL_FROM,string.join(EMAIL_TO,','),subject,formatdate(),msg)
    if not log2mailctx.check():
        return
    thread = Thread(target=sendLogMailFunc,args=(EMAIL_HOST,EMAIL_PORT,EMAIL_USERNAME,EMAIL_PASSWD,EMAIL_FROM,EMAIL_TO,msg))
    thread.start()


class ThreadedSSLSMTPHandler(logging.Handler):
    def emit(self,record):
        try:
            subject = EMAIL_SUBJECT + u'@' + log2mailctx.servername
            msg = self.format(record)
            sendLogMail(subject,msg)
        except (KeyboardInterrupt,SystemExit):
            raise
        except:
            self.handleError(record)

def setup(level,name):
    hostName = socket.gethostname() # VM-23-77-ubuntu
    myname = socket.getfqdn(hostName) # localhost.localdomain
    myaddr1 = socket.gethostbyname(hostName) # 127.0.0.1
    myaddr2 = socket.gethostbyname(myname) # 127.0.0.1
    log2mailctx.servername = u'%s<%s>' % (name,myname)
    logger = logging.getLogger()
    gm = ThreadedSSLSMTPHandler()
    gm.setLevel(level)
    logger.addHandler(gm)


if __name__ == '__main__':
    setup(logging.ERROR,u'aaaaaaaaaaaa')
    print('begin'+str(time.time()))
    try:
        1/0
    except:
        logging.exception("test")
        
    def sendMail2Admin(subject,msg):
        msg = "From:%s\r\nTo:%s\r\nSubject:%s\r\nDate:%s\r\n\r\n%s" % (EMAIL_FROM,string.join(EMAIL_TO,','),subject,formatdate(),msg)
        thread = Thread(target=sendMailFunc,args=(EMAIL_HOST,EMAIL_PORT,EMAIL_USERNAME,EMAIL_PASSWD,EMAIL_FROM,EMAIL_TO,msg))
        thread.start()
    #sendMail2Admin('sendmail2admin','message')
    print('end'+str(time.time()))